package org.jeecg.modules.business.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.modules.business.entity.BusHousePriceSchemeLayout;
import org.jeecg.modules.business.entity.BusSchemeLayoutDailyPrice;
import org.jeecg.modules.business.service.IBusHousePriceSchemeLayoutService;
import org.jeecg.modules.business.service.IBusSchemeLayoutDailyPriceService;
import org.jeecg.modules.rooms.entity.CesHousePriceScheme;
import org.jeecg.modules.rooms.entity.CesRoomLayout;
import org.jeecg.modules.rooms.service.CesHousePriceSchemeServiceImpl;
import org.jeecg.modules.rooms.service.CesRoomLayoutServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 房价方案-房型关联表
 * @Author: jeecg-boot
 * @Date:   2023-04-07
 * @Version: V1.0
 */
@Api(tags="房价方案-房型关联表")
@RestController
@RequestMapping("/business/busHousePriceSchemeLayout")
@Slf4j
public class BusHousePriceSchemeLayoutController extends JeecgController<BusHousePriceSchemeLayout, IBusHousePriceSchemeLayoutService> {
	@Autowired
	private IBusHousePriceSchemeLayoutService busHousePriceSchemeLayoutService;

	@Resource
	 private IBusSchemeLayoutDailyPriceService schemeLayoutDailyPriceService;
	 @Resource
	 private CesRoomLayoutServiceImpl cesRoomLayoutService;
	 @Resource
	 private CesHousePriceSchemeServiceImpl housePriceSchemeService;
	/**
	 * 分页列表查询
	 */
	//@AutoLog(value = "房价方案-房型关联表-分页列表查询")
	@ApiOperation(value="房价方案-房型关联表-分页列表查询", notes="房价方案-房型关联表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<BusHousePriceSchemeLayout>> queryPageList(BusHousePriceSchemeLayout busHousePriceSchemeLayout,
								   Integer type,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		if (type != null) {
			CesHousePriceScheme housePriceScheme = housePriceSchemeService.getOne(Wrappers.<CesHousePriceScheme>lambdaQuery()
					.eq(CesHousePriceScheme::getSchemeType,type).eq(CesHousePriceScheme::getHotelId, busHousePriceSchemeLayout.getHotelId()).last("limit 1"));
			busHousePriceSchemeLayout.setSchemeId(housePriceScheme.getId());
		}
		QueryWrapper<BusHousePriceSchemeLayout> queryWrapper = QueryGenerator.initQueryWrapper(busHousePriceSchemeLayout, req.getParameterMap());
		Page<BusHousePriceSchemeLayout> page = new Page<BusHousePriceSchemeLayout>(pageNo, pageSize);
		IPage<BusHousePriceSchemeLayout> pageList = busHousePriceSchemeLayoutService.page(page, queryWrapper);
		pageList.getRecords().forEach(item->{
			CesRoomLayout layout = cesRoomLayoutService.getById(item.getLayoutId());
			if (layout != null) {
				item.setLayoutName(layout.getName());
				item.setLayoutPrice(layout.getMarketPrice());
			}
		});
		return Result.OK(pageList);
	}


	 /**
	  * 重置每日房价
	  */
	 //@AutoLog(value = "房价方案-房型关联表-分页列表查询")
	 @ApiOperation(value="重置每日房价", notes="重置每日房价")
	 @GetMapping(value = "/resetDailyPrice")
	 public Result<Boolean> resetDailyPrice(String priceSchemeLayoutId) {
		 BusHousePriceSchemeLayout priceSchemeLayout = service.getById(priceSchemeLayoutId);
		 if (priceSchemeLayout == null){
			 return Result.error("未找到对应的 房价方案与房型关联");
		 }
		 schemeLayoutDailyPriceService.remove(Wrappers.<BusSchemeLayoutDailyPrice>lambdaQuery()
				 .eq(BusSchemeLayoutDailyPrice::getSchemeLayoutId, priceSchemeLayout.getId()));
		 return Result.OK("重置成功");
	 }


	 /**
	  * 分页列表查询
	  */
	 //@AutoLog(value = "房价方案-房型关联表-分页列表查询")
	 @ApiOperation(value="房价方案-房型关联表-分页列表查询", notes="房价方案-房型关联表-分页列表查询")
	 @GetMapping(value = "/layoutPricePage")
	 public Result<IPage<BusHousePriceSchemeLayout>> layoutPricePage(BusHousePriceSchemeLayout busHousePriceSchemeLayout,
																   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
																   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
																   HttpServletRequest req) {
		 QueryWrapper<BusHousePriceSchemeLayout> queryWrapper = QueryGenerator.initQueryWrapper(busHousePriceSchemeLayout, req.getParameterMap());
		 Page<BusHousePriceSchemeLayout> page = new Page<>(pageNo, pageSize);
		 IPage<BusHousePriceSchemeLayout> pageList = busHousePriceSchemeLayoutService.page(page, queryWrapper);
		 pageList.getRecords().forEach(item->{
			 CesRoomLayout layout = cesRoomLayoutService.getById(item.getLayoutId());
			 if (layout != null) {
				 item.setLayoutName(layout.getName());
				 item.setLayoutPrice(layout.getMarketPrice());
				 List<BusSchemeLayoutDailyPrice> dailyPrice = schemeLayoutDailyPriceService.getDailyPrice(item.getId(), null);
				 item.setSchemeLayoutDailyPriceList(dailyPrice);
			 }
		 });
		 return Result.OK(pageList);
	 }

	 /**
	  * 列表查询
	  */
	 //@AutoLog(value = "房价方案-房型关联表-列表查询")
	 @ApiOperation(value="房价方案-房型关联表-列表查询", notes="房价方案-房型关联表-列表查询")
	 @GetMapping(value = "/queryList")
	 public Result<List<BusHousePriceSchemeLayout>> queryList(BusHousePriceSchemeLayout busHousePriceSchemeLayout, HttpServletRequest req) {
		 QueryWrapper<BusHousePriceSchemeLayout> queryWrapper = QueryGenerator.initQueryWrapper(busHousePriceSchemeLayout, req.getParameterMap());
		 LoginUser user = TokenUtils.getAuthUser();
		 if(user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")){
			 queryWrapper.eq("tenant_id",user.getRelTenantIds());
		 }
		 queryWrapper.eq("del_flag",0);
		 List<BusHousePriceSchemeLayout> list = busHousePriceSchemeLayoutService.list(queryWrapper);
		 return Result.OK(list);
	 }

	 /**
	  * 分页列表查询
	  */
	 //@AutoLog(value = "房价方案-房型关联表-分页列表查询")
	 @ApiOperation(value="房价方案-房型关联表-分页列表查询", notes="房价方案-房型关联表-分页列表查询")
	 @PostMapping(value = "/getSchemeLayoutByLayoutId")
	 public Result<List<CesHousePriceScheme>> getSchemeLayoutByLayoutId(@RequestBody List<String> layoutIds,String hotelId) {
		 if (CollUtil.isEmpty(layoutIds)){
			 return null;
		 }
		 // 房价方案
		 LambdaQueryWrapper<CesHousePriceScheme> queryWrapper = new LambdaQueryWrapper<>();
		 queryWrapper.eq(CesHousePriceScheme::getHotelId,hotelId);
		 queryWrapper.eq(CesHousePriceScheme::getInvalid,false);
		 queryWrapper.eq(CesHousePriceScheme::getOpen,1);
		 queryWrapper.and(e -> e.le(CesHousePriceScheme::getValidStartTime, LocalDate.now())
				 .ge(CesHousePriceScheme::getValidEndTime, LocalDate.now()).or().eq(CesHousePriceScheme::getValidTime, 0));
		 queryWrapper.and(e -> e.le(CesHousePriceScheme::getStartTime, LocalTime.now())
				 .ge(CesHousePriceScheme::getEndTime, LocalTime.now()).or().eq(CesHousePriceScheme::getCheckInTime, 0));
		 List<CesHousePriceScheme> cesHousePriceSchemes = housePriceSchemeService.list(queryWrapper);
		 List<String> priceSchemeIds = cesHousePriceSchemes.stream().map(CesHousePriceScheme::getId).collect(Collectors.toList());
		 if (CollUtil.isEmpty(priceSchemeIds)){
			 throw new JeecgBootException("未找到方案");
		 }
		 // 房价方案房型
		 List<BusHousePriceSchemeLayout> schemeLayouts = busHousePriceSchemeLayoutService.list(Wrappers.<BusHousePriceSchemeLayout>lambdaQuery()
				 .eq(BusHousePriceSchemeLayout::getDelFlag, 0).in(BusHousePriceSchemeLayout::getLayoutId, layoutIds));
		 List<String> ids = schemeLayouts.stream().map(BusHousePriceSchemeLayout::getId).collect(Collectors.toList());
		 if (CollUtil.isEmpty(ids)){
			 return null;
		 }
		 // 房价方案房型 自定义的每天价格
		 List<BusSchemeLayoutDailyPrice> dailyPrices = schemeLayoutDailyPriceService.list(Wrappers
				 .<BusSchemeLayoutDailyPrice>lambdaQuery().in(BusSchemeLayoutDailyPrice::getSchemeLayoutId, ids));
		 schemeLayouts.forEach(e -> {
			 List<BusSchemeLayoutDailyPrice> layoutDailyPrices = dailyPrices.stream().filter(ele ->
					 StrUtil.equals(e.getId(), ele.getSchemeLayoutId())).collect(Collectors.toList());
			 e.setSchemeLayoutDailyPriceList(layoutDailyPrices);
		 });
		 cesHousePriceSchemes.forEach(e -> {
			 List<BusHousePriceSchemeLayout> findSchemeLayouts = schemeLayouts.stream().filter(ele -> StrUtil.equals(e.getId(), ele.getSchemeId())).collect(Collectors.toList());
			 e.setSchemeLayouts(findSchemeLayouts);
		 });
		 return Result.OK(cesHousePriceSchemes);
	 }


	/**
	 *   添加
	 */
	@AutoLog(value = "房价方案-房型关联表-添加")
	@ApiOperation(value="房价方案-房型关联表-添加", notes="房价方案-房型关联表-添加")
	//@RequiresPermissions("business:bus_house_price_scheme_layout_info:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BusHousePriceSchemeLayout busHousePriceSchemeLayout) {
		busHousePriceSchemeLayoutService.save(busHousePriceSchemeLayout);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 */
	@AutoLog(value = "房价方案-房型关联表-编辑")
	@ApiOperation(value="房价方案-房型关联表-编辑", notes="房价方案-房型关联表-编辑")
	//@RequiresPermissions("business:bus_house_price_scheme_layout_info:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody BusHousePriceSchemeLayout busHousePriceSchemeLayout) {
		busHousePriceSchemeLayoutService.updateById(busHousePriceSchemeLayout);
		return Result.OK("编辑成功!");
	}

	 /**
	  *  编辑
	  */
	 @AutoLog(value = "房价方案-房型关联表-编辑")
	 @ApiOperation(value="房价方案-房型关联表-编辑", notes="房价方案-房型关联表-编辑")
	 //@RequiresPermissions("business:bus_night_trial_info:edit")
	 @RequestMapping(value = "/editMoney", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<BusHousePriceSchemeLayout> editMoney(@RequestBody BusHousePriceSchemeLayout busHousePriceSchemeLayout) {
		 if(busHousePriceSchemeLayout.getTenantId() == null || busHousePriceSchemeLayout.getTenantId().equals("")){
			 LoginUser user = TokenUtils.getAuthUser();
			 if(user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")){
				 busHousePriceSchemeLayout.setTenantId(user.getRelTenantIds());
			 } else {
				 throw new JeecgBootException("当前登录人租户信息错误");
			 }
		 }
		 BusHousePriceSchemeLayout editModel = busHousePriceSchemeLayoutService.getById(busHousePriceSchemeLayout.getId());
		 editModel.setMoney(busHousePriceSchemeLayout.getMoney());
		 busHousePriceSchemeLayoutService.updateById(editModel);
		 return Result.OK(editModel);
	 }

	 /**
	  *  编辑
	  *
	  * @param busHousePriceSchemeLayout
	  * @return
	  */
	 @AutoLog(value = "房价方案-房型关联表-编辑")
	 @ApiOperation(value="房价方案-房型关联表-编辑", notes="房价方案-房型关联表-编辑")
	 @RequestMapping(value = "/editNumber", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<BusHousePriceSchemeLayout> editNumber(@RequestBody BusHousePriceSchemeLayout busHousePriceSchemeLayout) {
		 if(busHousePriceSchemeLayout.getTenantId() == null || busHousePriceSchemeLayout.getTenantId().equals("")){
			 LoginUser user = TokenUtils.getAuthUser();
			 if(user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")){
				 busHousePriceSchemeLayout.setTenantId(user.getRelTenantIds());
			 } else {
				 throw new JeecgBootException("当前登录人租户信息错误");
			 }
		 }
		 BusHousePriceSchemeLayout editModel = busHousePriceSchemeLayoutService.getById(busHousePriceSchemeLayout.getId());
		 editModel.setBreakfastNumber(busHousePriceSchemeLayout.getBreakfastNumber());
		 busHousePriceSchemeLayoutService.updateById(editModel);
		 return Result.OK(editModel);
	 }

	 /**
	  *  编辑
	  *
	  * @param busHousePriceSchemeLayout
	  * @return
	  */
	 @AutoLog(value = "房价方案-房型关联表-编辑")
	 @ApiOperation(value="房价方案-房型关联表-编辑", notes="房价方案-房型关联表-编辑")
	 @RequestMapping(value = "/editTime", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<BusHousePriceSchemeLayout> editTime(@RequestBody BusHousePriceSchemeLayout busHousePriceSchemeLayout) {
		 if(busHousePriceSchemeLayout.getTenantId() == null || busHousePriceSchemeLayout.getTenantId().equals("")){
			 LoginUser user = TokenUtils.getAuthUser();
			 if(user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")){
				 busHousePriceSchemeLayout.setTenantId(user.getRelTenantIds());
			 } else {
				 throw new JeecgBootException("当前登录人租户信息错误");
			 }
		 }
		 BusHousePriceSchemeLayout editModel = busHousePriceSchemeLayoutService.getById(busHousePriceSchemeLayout.getId());
		 editModel.setDepartureTime(busHousePriceSchemeLayout.getDepartureTime());
		 busHousePriceSchemeLayoutService.updateById(editModel);
		 return Result.OK(editModel);
	 }
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "房价方案-房型关联表-通过id删除")
	@ApiOperation(value="房价方案-房型关联表-通过id删除", notes="房价方案-房型关联表-通过id删除")
	//@RequiresPermissions("business:bus_house_price_scheme_layout_info:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		busHousePriceSchemeLayoutService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "房价方案-房型关联表-批量删除")
	@ApiOperation(value="房价方案-房型关联表-批量删除", notes="房价方案-房型关联表-批量删除")
	//@RequiresPermissions("business:bus_house_price_scheme_layout_info:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.busHousePriceSchemeLayoutService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "房价方案-房型关联表-通过id查询")
	@ApiOperation(value="房价方案-房型关联表-通过id查询", notes="房价方案-房型关联表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<BusHousePriceSchemeLayout> queryById(@RequestParam(name="id",required=true) String id) {
		BusHousePriceSchemeLayout busHousePriceSchemeLayout = busHousePriceSchemeLayoutService.getById(id);
		if(busHousePriceSchemeLayout==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(busHousePriceSchemeLayout);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param busHousePriceSchemeLayout
    */
    //@RequiresPermissions("business:bus_house_price_scheme_layout_info:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BusHousePriceSchemeLayout busHousePriceSchemeLayout) {
        return super.exportXls(request, busHousePriceSchemeLayout, BusHousePriceSchemeLayout.class, "房价方案-房型关联表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("business:bus_house_price_scheme_layout_info:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, BusHousePriceSchemeLayout.class);
    }

}
